package com.example.lib_mvp.views;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

public class SpectrumView extends View {
    private Paint paint;
    private float[] amplitudes = new float[256];
    private float maxHeight = 100f; // Maximum height of the bars
    private float speed = 2f; // Speed of the animation
    private float jumpAmplitude = 10f; // Amplitude of the jump effect
    private float barSpacing = 5f; // Spacing between bars

    public SpectrumView(Context context) {
        super(context);
        init();
    }

    public SpectrumView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public SpectrumView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        paint = new Paint();
        paint.setColor(Color.BLUE);
        paint.setStyle(Paint.Style.FILL);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int width = getWidth();
        int height = getHeight();
        int barCount = amplitudes.length;
        int barWidth = (width - (barCount - 1) * (int) barSpacing) / barCount;

        for (int i = 0; i < barCount; i++) {
            float amplitude = amplitudes[i];
            float barHeight = (amplitude / 255f) * maxHeight;

            // Add jump effect
            float jump = (float) Math.sin(System.currentTimeMillis() / 100.0 + i) * jumpAmplitude;

            // Calculate bar position
            int x = i * (barWidth + (int) barSpacing);

            // Draw the bar
            canvas.drawRect(x, height - barHeight - jump, x + barWidth, height, paint);
        }

        // Request to redraw
        invalidate();
    }

    public void setAmplitudes(float[] amplitudes) {
        this.amplitudes = amplitudes;
        invalidate(); // Request initial draw
    }

    public void setMaxHeight(float maxHeight) {
        this.maxHeight = maxHeight;
        invalidate(); // Request redraw
    }

    public void setSpeed(float speed) {
        this.speed = speed;
        invalidate(); // Request redraw
    }

    public void setJumpAmplitude(float jumpAmplitude) {
        this.jumpAmplitude = jumpAmplitude;
        invalidate(); // Request redraw
    }

    public void setBarSpacing(float barSpacing) {
        this.barSpacing = barSpacing;
        invalidate(); // Request redraw
    }
}
